<template>
  <Form ref="formValidate"  :label-width="120" :model="formData" @submit.native.prevent>
    <div style="text-align:center;margin-bottom: 20px" >
      <h2>{{formTemplate.formName}}</h2>
    </div>
    <renders v-for="(element,index) in template_form" :key="index" :index="index" :ele="element.ele" :obj="element.obj || {}" :data="formData" @handleChangeVal="val => handleChangeVal(val,element)" @changeVisibility="changeVisibility" :value="formData[element.obj.name]" :sortableItem="template_form" :disabled="readOnly" :configIcon="configIcon">
    </renders>
  </Form>
</template>
<script>
    import api  from '../../../libs/api';
    import {eventBus}  from '../../../libs/eventBus';
    import elementUtil from "./custom_form/Preview"
    export default {
        name: 'preview',
        props:["formTemplate","mode","formTemplateId","formRecordId"],
        data() {
            return {
                template_form: [],
                formData: {},
                formName:"",
                configIcon:false,
                readOnly:false,
                formElements:["select","radio","checkbox"],  //需要保存table显示列的组件类型
            }
        },
        methods: {
            //迭代循环
            hanleCascaderLoop(cascader,datas,value,multiple){
                let split=multiple?",":"/";
                let self=this;
                let hit=[];
                hit=datas.filter(v => {
                    return v.value==value;
                });
                if(hit.length>0){
                    cascader.display+=hit[0].label+split;
                    return hit[0].label;
                }else{
                    datas.forEach(function (data) {
                        if(typeof data.children!="undefined"&&data.children!=null&&data.children.length>0)
                            return self.hanleCascaderLoop(cascader,data.children,value);
                    });
                }
            },
            //获取cascader的显示值
            handleCascader(data,values,multiple){
                let self=this;
                let cascader={display:""};
                values.forEach(function (value) {
                    self.hanleCascaderLoop(cascader,data,value,multiple);
                });
                if(cascader.display!=""){
                    cascader.display=cascader.display.substring(0,cascader.display.length-1);
                }
                return cascader.display;
            },
            // 控件回填数据
            handleChangeVal(val, element) {
                this.$set(this.formData, element.obj.name, val);
                // this.formData[element.obj.name] = val;
            },
            // 更改当前渲染字段是否显示
            changeVisibility(index, visibility) {
                this.$set(this.template_form[index].obj, 'visibility', visibility);
            },
            //查看表单记录
            handleFormRecordView(){
                this.readOnly=true;
                this.handleFormRecord(true);

            },
            //加载数据
            handleFormRecord(tinymceReadOnly){
                let self=this;
                self.$get(api.formTemplates.record.base.replace("{templateId}",self.formTemplateId)+"/"+ self.formRecordId,{}).then(response=>{
                    if(200==response.code){
                        for(let i in self.template_form){
                            response.obj.forEach(function(element){
                                if(element.name==self.template_form[i].obj.name){
                                    self.template_form[i].obj.value=element.valueView;
                                    self.template_form[i].obj.id=element.id;
                                    self.$set(self.formData, self.template_form[i].obj.name, self.template_form[i].obj.value);
                                    //富文本处理
                                    if(element.element=="tinymce"){
                                        let index=(typeof tinyMCE.editors[1] !="undefined")?1:0;
                                        let tinymceInstance;
                                        if(index==1){
                                            tinymceInstance= tinyMCE.activeEditor;
                                        }else{
                                            tinymceInstance=  tinyMCE.get(tinyMCE.editors[index].id);
                                        }
                                        setTimeout(function () {
                                            tinymceInstance.setContent(self.template_form[i].obj.value);
                                            tinymceReadOnly&&tinymceInstance.setMode('readonly');
                                        },1000);
                                    }
                                }
                            })
                        }
                    }
                });
            },
            //编辑表单记录
            handleFormRecordEdit(){
                this.readOnly=false;
                this.handleFormRecord(false);
            },
            //查看模板模式
            handleFormTemplateView(){
            }
        },
        created() {
            this.formName=this.formTemplate.formName;
            this.template_form = JSON.parse(this.formTemplate.formTemplate);
        },

        mounted(){
            let self=this;
            switch(self.mode){  //预览模式
                case "formRecordView":{  //记录查看
                    self.handleFormRecordView();
                }
                break;
                case "formRecordEdit":{
                    self.handleFormRecordEdit(); //记录编辑
                }
                break;
                case "formTemplateView":{     //预览模板
                    self.configIcon=true;
                }
                break;
                default:"";
            }
            //更新表单数据
            eventBus.$on("updateFormRecord",function (formTemplateId,formRecordId,modal) {
                (typeof self.$refs["formValidate"]!="undefined")&&self.$refs["formValidate"].validate((valid) => {
                  if (valid) {
                      let formDataView=[];
                      let formRecord={};
                      self.template_form.forEach(function(item){
                          const formData={};
                          formData.id=item.obj.id;//主键
                          formData.element=item.ele; //元素类型
                          formData.name=item.obj.name; //元素name属性
                          formData.label=item.obj.label;//元素显示
                          formData.formRecordId=formRecordId;
                          formData.dictionaryId=(typeof (item.obj.dict)!="undefined")?JSON.parse(item.obj.dict).id:""; //数据字典
                          switch(item.ele){
                              case "uploads":{          //附件上传
                                  let uploads=[];
                                  item.obj.value.forEach(function(upload){
                                      uploads.push(upload.id);
                                  });
                                  formData.value=uploads.toString();
                              };
                              break;
                              case "address":    //地址组件
                              case "checkbox":{  //复选框组件
                                  formData.value=item.obj.value.toString();
                              }
                              break;
                              case "cascader":{
                                  formData.additional=self.handleCascader(item.obj.data,item.obj.value,item.obj.multiple);
                                  formData.value=item.obj.value.toString();
                              }
                              break;
                              case "datepicker":{
                                  formData.value=item.obj.value;
                                  formData.additional=item.obj.format;
                              }
                              break;
                              default: formData.value=item.obj.value;
                          }
                          formDataView.push(formData);
                          formRecord.formTemplateId=formTemplateId;
                          formRecord.formDataView=formDataView;
                      });
                      self.$put(api.formTemplates.record.base.replace("{templateId}",formTemplateId)+"/"+formRecordId,formRecord).then(response=>{
                          if(200==response.code){
                              this.$Modal.remove();
                              eventBus.$emit("freshFormRecord");
                          }
                      })
                  }
                });
            }
        );
        //新增表单
        eventBus.$on("addFormRecord",function (formTemplateId) {
            (typeof self.$refs["formValidate"]!="undefined")&&self.$refs["formValidate"].validate((valid) => {
                if (valid) {
                    let formDataView=[];
                    let formRecord={};
                    self.template_form.forEach(function(item){
                        const formData={};
                        formData.element=item.ele; //元素类型
                        formData.name=item.obj.name; //元素name属性
                        formData.label=item.obj.label;//元素显示
                        formData.dictionaryId=(typeof (item.obj.dict)!="undefined")?JSON.parse(item.obj.dict).id:""; //数据字典
                        switch(item.ele){
                            case "uploads":{          //附件上传
                                let uploads=[];
                                item.obj.value.forEach(function(upload){
                                    uploads.push(upload.id);
                                });
                                formData.value=uploads.toString();
                            };
                            break;
                            case "address":    //地址组件
                            case "checkbox":{  //复选框组件
                                formData.value=item.obj.value.toString();
                            }
                            break;
                            case "cascader":{
                                formData.additional=self.handleCascader(item.obj.data,item.obj.value,item.obj.multiple);
                                formData.value=item.obj.value.toString();
                            }
                            break;
                            case "datepicker":{
                                formData.value=item.obj.value;
                                formData.additional=item.obj.format;
                            }
                            break;
                            default: formData.value=item.obj.value;
                        }
                        formDataView.push(formData);
                        formRecord.formTemplateId=formTemplateId;
                        formRecord.formDataView=formDataView;
                    });
                    self.$post(api.formTemplates.record.base.replace("{templateId}",formRecord.formTemplateId),formRecord).then(response=>{
                        if(200==response.code){
                            this.$Modal.remove();
                            eventBus.$emit("freshFormRecord",{formTemplateId:formTemplateId});
                        }
                    })
                }
            });
        })

    }
    }
</script>
<style>


</style>
